package org.lemon.cla.serviceImp;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.lemon.cla.pojo.User;
import org.lemon.cla.mapper.UserMapper; // 假设你有 UserMapper
import org.lemon.cla.service.IUserService;
import org.lemon.cla.dto.request.UserSearchRequest;
import org.lemon.cla.dto.response.UserResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Override
    public IPage<UserResponse> searchUsersByConditions(Page<UserResponse> page, UserSearchRequest request) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        // 1. 用户名模糊查询
        if (request.getUsername() != null && !request.getUsername().isEmpty()) {
            queryWrapper.like("username", request.getUsername());
        }

        // 2. 角色精确匹配
        if (request.getRole() != null) {
            queryWrapper.eq("role", request.getRole()); // MyBatis-Plus 会自动处理枚举
        }

        // 3. 真名模糊查询
        if (request.getRealName() != null && !request.getRealName().isEmpty()) {
            queryWrapper.like("real_name", request.getRealName());
        }

        // 4. 手机号模糊查询
        if (request.getPhone() != null && !request.getPhone().isEmpty()) {
            queryWrapper.like("phone", request.getPhone());
        }

        // 5. 邮箱模糊查询
        if (request.getEmail() != null && !request.getEmail().isEmpty()) {
            queryWrapper.like("email", request.getEmail());
        }

        // 7. 创建时间范围查询
        if (request.getCreateTimeStart() != null) {
            queryWrapper.ge("create_time", request.getCreateTimeStart());
        }
        if (request.getCreateTimeEnd() != null) {
            queryWrapper.le("create_time", request.getCreateTimeEnd());
        }

        // 默认排序
        queryWrapper.orderByDesc("create_time");

        // 执行分页查询，返回 IPage<User>
        IPage<User> userIPage = baseMapper.selectPage(new Page<>(page.getCurrent(), page.getSize()), queryWrapper);

        // 将 IPage<User> 转换为 IPage<UserResponse> (移除密码)
        List<UserResponse> userResponses = userIPage.getRecords().stream()
                .map(user -> {
                    UserResponse userResponse = new UserResponse();
                    BeanUtils.copyProperties(user, userResponse);
                    return userResponse;
                })
                .collect(Collectors.toList());

        // 创建新的 IPage<UserResponse> 结果
        Page<UserResponse> resultPage = new Page<>(userIPage.getCurrent(), userIPage.getSize(), userIPage.getTotal());
        resultPage.setRecords(userResponses);
        resultPage.setPages(userIPage.getPages()); // 确保总页数也传递

        return resultPage;
    }

    @Override
    public User getUserByUsername(String username) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public boolean setLogicalDeleteStatus(Integer userId, boolean deleteStatus) {
        // 创建 UpdateWrapper 来精确指定要更新的字段和条件
        UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
        updateWrapper
                .eq("user_id", userId) // 更新条件：根据用户ID
                .set("is_deleted", deleteStatus); // 设置要更新的字段和值

        // 使用 update(entity, wrapper) 方法。这里 entity 可以是 null，或者一个只包含主键的实体
        // 因为所有更新的字段和条件都在 wrapper 中指定了。
        return baseMapper.update(null, updateWrapper) > 0; // baseMapper.update 返回受影响行数
    }
}